/**
 * 
 */
package com.ibuonline.search.solr.extend.dao;

import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.dimeng.commons.dao.hibernate.HibernateDao;
import com.ibuonline.search.solr.extend.model.Product;

/**
 * @author Liuye
 * 
 */
@Repository
public class ProductDao extends HibernateDao<Product, Long> {
	private static final String QUERY_SCORE = "SELECT score FROM product WHERE id=?";
	private static final String QUERY_ALL_SCORE = "SELECT id,score FROM product";

	public Float getScore(final Long id) {
		return (Float) getHibernateTemplate().executeWithNativeSession(
				new HibernateCallback() {
					public Object doInHibernate(final Session session)
							throws HibernateException {
						final Query q = session.createSQLQuery(QUERY_SCORE)
								.addScalar("score", StandardBasicTypes.FLOAT);
						q.setParameter(0, id);
						q.setMaxResults(1);
						List<Float> result = q.list();
						if (result.size() > 0) {
							return result.get(0);
						}
						return 0f;
					}
				});
	}

	public List<Map<String, Object>> getAllScores() {
		return getHibernateTemplate().executeWithNativeSession(
				new HibernateCallback() {
					public Object doInHibernate(final Session session)
							throws HibernateException {
						final Query q = session.createSQLQuery(QUERY_ALL_SCORE)
								.addScalar("id", StandardBasicTypes.LONG)
								.addScalar("score", StandardBasicTypes.FLOAT);
						q.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
						return q.list();
					}
				});
	}
}
